import { Component, OnInit, HostBinding, Input, AfterContentInit, ElementRef, HostListener, ViewChild, TemplateRef } from '@angular/core';
import { SelectStoreService } from './select-store.service';

@Component({
  selector: 'fui-select-option-all',
  templateUrl: './select-option-all.component.html',
})
export class SelectOptionAllComponent implements OnInit, AfterContentInit {

  @HostBinding('attr.disabled') get attrDisabled() {
    return this.disabled;
  }

  @ViewChild(TemplateRef) template: TemplateRef<void>;

  /** Disabled state. */
  @Input() disabled: boolean;

  hasContent = true;

  constructor(
    private elementRef: ElementRef,
    public store: SelectStoreService,
  ) { }

  ngOnInit() {
    if (this.store.mode === 'single') {
      throw Error('Cannot use fui-select-option-all with single mode. Please use <fui-select mode="multiple"...');
    }
  }

  ngAfterContentInit() {
    const element: HTMLElement = this.elementRef.nativeElement;
    if (element.textContent.trim().length === 0) {
      this.hasContent = false;
    }
  }

  clickHandler(event: MouseEvent) {
    event.preventDefault();
    if (!this.disabled) {
      const value = !this.store.allSelected;
      this.store.selectAll(value);
    }
  }

}
